package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"user/echa"
	"user/models"
)

type BooksController struct {
	beego.Controller
}
type Msg struct {
	Code     int
	Msg      string
	Database interface{}
}

func (c *BooksController) Add() {
	title := c.GetString("title")
	lm := c.GetString("lm")
	name := c.GetString("name")
	zhuangtai := c.GetString("zhuangtai")
	ss := models.Books{
		Title:     title,
		Lm:        lm,
		Name:      name,
		Zhuangtai: zhuangtai,
	}
	if title == "" || lm == "" || name == "" || zhuangtai == "" {
		res := Msg{
			Code: 0,
			Msg:  "数据不能为空",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	err := models.DB.Debug().Create(&ss).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "添加失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		key := fmt.Sprintf("books_add_%d", ss.ID)
		jsonData, _ := json.Marshal(ss)
		echa.Rdb.Set(echa.Ctx, key, jsonData, 0)
		res := Msg{
			Code: 200,
			Msg:  "添加成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}

}
func (c *BooksController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var alloct []models.Books
	err := models.DB.Debug().Find(&alloct).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "查询失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code:     200,
			Msg:      "查询成功",
			Database: alloct,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *BooksController) Update() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	lm := c.GetString("lm")
	name := c.GetString("name")
	zhuangtai := c.GetString("zhuangtai")
	ss := models.Books{
		Title:     title,
		Lm:        lm,
		Name:      name,
		Zhuangtai: zhuangtai,
	}
	err := models.DB.Debug().Where("id=?", id).Updates(&ss).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "修改失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		key := fmt.Sprintf("books_add_%d", ss.ID)
		jsonData, _ := json.Marshal(ss)
		echa.Rdb.Set(echa.Ctx, key, jsonData, 0)
		res := Msg{
			Code: 200,
			Msg:  "修改成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *BooksController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Debug().Delete(&models.Books{}, id).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "删除失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		key := fmt.Sprintf("books_del_%d", id)
		jsonData, _ := json.Marshal(id)
		echa.Rdb.Set(echa.Ctx, key, jsonData, 0)
		res := Msg{
			Code: 200,
			Msg:  "删除成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
